package com.findviewbydream.evil.eda;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.findviewbydream.evil.eda.Answer.AnswerActivity;
import com.findviewbydream.evil.eda.Answer.ItemListActivity;
import com.findviewbydream.evil.eda.Data.Data;
import com.findviewbydream.evil.eda.Data.UserData;
import com.findviewbydream.evil.eda.EventBus.AnswerResultEvent;
import com.findviewbydream.evil.eda.Utils.Utils;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wooplr.spotlight.SpotlightView;
import com.yuyh.easyadapter.recyclerview.EasyRVAdapter;
import com.yuyh.easyadapter.recyclerview.EasyRVHolder;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.iwgang.familiarrecyclerview.FamiliarRecyclerView;
import okhttp3.Call;

/********************************************
 * 工程名：Eda
 * 包名：com.findviewbydream.evil.eda
 * 时间：16-10-13 下午4:25
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：将首页改为list的补丁，以后弃用
 ********************************************/
public class MainActivity_Include_Patch extends MainActivity
{
    public static final String FLOW_TYPE = "flowType";
    private static final String TYPE_GETLIST = "getList";

    private FamiliarRecyclerView recyclerView;
    private CoordinatorLayout coordinatorLayout;
    private SpinKitView loading;

    private Adapter adapter;

    private ArrayList<ItemBean> list;

    @Override
    protected void setList()
    {
        Utils.Logger("进入");
        initView();/*控件初始化*/
        setRecyclerView();/*设置RecyclerView*/
        toNetWork();/*网络加载*/
    }

    /**
     * 控件初始化
     */
    private void initView()
    {
        recyclerView = (FamiliarRecyclerView) findViewById(R.id.recyclerView);
        loading = (SpinKitView) findViewById(R.id.loading);
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
    }

    /**
     * 设置RecyclerView
     */
    private void setRecyclerView()
    {
        list = new ArrayList<>();
        adapter = new Adapter(this, list, R.layout.itemlist_item);
        recyclerView.setAdapter(adapter);

        recyclerView.setOnItemClickListener((familiarRecyclerView, view, position)
                -> startActivity(new Intent(MainActivity_Include_Patch.this, AnswerActivity.class)
                .putExtra("itemId", list.get(position).itemId)
                .putExtra("position", position)));
    }

    /**
     * 网络加载
     */
    private void toNetWork()
    {
        loading.setVisibility(View.VISIBLE);
        String lastItemId;

        list.clear();/*todo：暂时办法，以后取消(因为当前是直接加载全部的题目，所以也就没有刷新的必要。清空列表，让最后一个值为0，重新加载列表)*/

        if (list != null && list.size() != 0)
            lastItemId = list.get(0).itemId + "";
        else
            lastItemId = "0";

        OkHttpUtils.post().url(Data.IP + "ItemListServlet")
                .addParams("phone", UserData.getUserPhoneNum())
                .addParams("imei", "" + UserData.getUserIMEI())
                .addParams("lastItemId", lastItemId)
                .addParams("type", TYPE_GETLIST)
                .addParams("flowType", "ALL")
               /* .addParams("flowType", getIntent().getStringExtra(FLOW_TYPE))*/
                .build()
                .execute(new StringCallback()
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        recyclerView.setVisibility(View.VISIBLE);
                        loading.setVisibility(View.GONE);

                        //NetUtils.reportError(this, e);
                        Snackbar.make(MainActivity_Include_Patch.this.findViewById(R.id.coordinatorLayout)
                                , "啊哦，获取列表失败了……"
                                , Snackbar.LENGTH_LONG)
                                .setAction("重试", view -> toNetWork()).show();
                    }

                    @Override
                    public void onResponse(String response, int id)
                    {
                        recyclerView.setVisibility(View.VISIBLE);
                        loading.setVisibility(View.GONE);

                        List<ItemListBean> beanList = new Gson().fromJson(response
                                , new TypeToken<List<ItemListBean>>()
                                {
                                }.getType());
                        if (beanList == null || beanList.size() == 0)
                        {
                            findViewById(R.id.null_sign).setVisibility(View.VISIBLE);
                            ImageView img = (ImageView) findViewById(R.id.imageView);
                            Utils.Glide(R.drawable.itemlist_nothing, img);
                        }
                        else
                        {
                            list.clear();
                            for (int i = 0; i < beanList.size(); i++)
                            {
                                ItemListBean bean = beanList.get(i);
                                list.add(new ItemBean(bean.id, bean.imgPath
                                        , bean.title, bean.answer_ids, bean.flow
                                        , bean.createTime, bean.overTime, bean.enabled));
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }
                });

    }


    /*EventBus -> 题目答完，删除该item*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AnswerResultEvent event)
    {
        Utils.Logger(event.position);
        list.remove(event.position);
        adapter.notifyDataSetChanged();
    }

    /**
     * 列表适配器
     */
    private class Adapter extends EasyRVAdapter<ItemBean>
    {
        public Adapter(Context context, List<ItemBean> list, int... layoutIds)
        {
            super(context, list, layoutIds);
        }

        @Override
        protected void onBindData(EasyRVHolder viewHolder, int position, ItemBean item)
        {
            ImageView img = viewHolder.getView(R.id.item_img);
            TextView title = viewHolder.getView(R.id.item_title);
            TextView maxDate = viewHolder.getView(R.id.item_maxdate);
            TextView flow = viewHolder.getView(R.id.item_tag);

            Utils.Glide(Utils.getNetImg(item.imgPath), img);
            title.setText(item.title);
            title.setTypeface(Typeface.DEFAULT_BOLD);
            maxDate.setText("限期:" + item.overTime + " 止");
            flow.setText(" " + item.flow + "M");

            if (item.isOverdue)
                viewHolder.getView(R.id.item_isOverdue).setVisibility(View.GONE);
            else
                viewHolder.getView(R.id.item_isOverdue).setVisibility(View.VISIBLE);
        }
    }


    private class ItemBean
    {
        private int itemId;
        private String imgPath;
        private String title;
        private String[] answer_ids;
        private int flow;
        private String createTime;
        private String overTime;
        private boolean isOverdue;

        public ItemBean(int itemId, String imgPath, String title, String[] answer_ids, int flow, String createTime, String overTime, boolean isOverdue)
        {
            this.itemId = itemId;
            this.imgPath = imgPath;
            this.title = title;
            this.answer_ids = answer_ids;
            this.flow = flow;
            this.createTime = createTime;
            this.overTime = overTime;
            this.isOverdue = isOverdue;
        }
    }

    private class ItemListBean
    {
        private int id;
        private String imgPath;
        private String title;
        private String[] answer_ids;
        private int type;
        private int flow;
        private boolean enabled;
        private String createTime;
        private String overTime;
    }
}
